package com.fh.shop.admin.util;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.DeleteObjectsRequest;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

public class OSSUtil {
    // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
    private static final String ENDPOINT = "https://oss-cn-hangzhou.aliyuncs.com";
    // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
    private static final String ACCESSKEYID = "LTAI5t8LGXCAZf1jb3WFBpsc";
    private static final String ACCESSKEYSECRET = "3Trg1z77LV2boe9FNyKxdewyfitSws";
    // 填写Bucket名称，例如examplebucket。
    private static final String BUCKETNAME = "fh-lius";
    //完整前缀
    private static final String PREFIX = "https://fh-lius.oss-cn-hangzhou.aliyuncs.com/";
    // 创建OSSClient实例。
    private static OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESSKEYID, ACCESSKEYSECRET);

    public static String upload(InputStream is,String fileName){
        try {
            //根据下标截取得到文件后缀
            String suffix = FileUtil.getSuffix(fileName);
            //得到文件夹名
            String folder = DateUtils.date2str(new Date(), DateUtils.Y_M_D);
            //得到新的文件名
            String filePath = folder + "/" + UUID.randomUUID() + suffix;
            // 创建PutObject请求。
            ossClient.putObject(BUCKETNAME, filePath, is);
            //返回全路径
            return PREFIX + filePath;
        } catch (OSSException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } catch (ClientException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            if (is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void deleteFile(String filePath){
        try {
            //将全路径替换为文件路径
            String path = filePath.replace(PREFIX, "");
            // 删除文件或目录。如果要删除目录，目录必须为空。
            ossClient.deleteObject(BUCKETNAME, path);
        } catch (OSSException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }

    public static void deleteBatchFile(List<String> keys){
        try {
            //将传过来的集合遍历并把每一项前缀都替换成空字符串 收集成新的集合
            List<String> paths = keys.stream().map(x -> x.replace(PREFIX, "")).collect(Collectors.toList());
            //根据集合进行批量删除
            ossClient.deleteObjects(new DeleteObjectsRequest(BUCKETNAME).withKeys(paths).withEncodingType("url"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
